package Thread.New.带返回值的线程创建.线程工具;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

    /**
     * @author 君未洋
     */
    public class CountDownLatch_Use {
        public static void main(String[] args) {
            //等待2个子线程执行完毕，计数器为2
            CountDownLatch countDownLatch = new CountDownLatch(2);
            System.out.println("开始执行主线程,并启动子线程");
            //创建并开启2个子线程
            SubThread subThread1 = new SubThread(countDownLatch);
            SubThread subThread2 = new SubThread(countDownLatch);
            subThread1.start();
            subThread2.start();

            try {
                //阻塞主线程，等待子线程结束
                System.out.println("主线程进入等待");
                countDownLatch.await();
                //只有等其他线程使用countDown()方法的时候才会启动主线程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("主线程执行完毕");
        }
    }

    class SubThread extends Thread {
        private CountDownLatch countDownLatch;

        public SubThread(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            //模拟执行任务
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //子线程执行完毕，减少计数器
            System.out.println(getName() + " 执行完毕");
            countDownLatch.countDown();
        }
    }